import React, { useState, useEffect, useContext } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import { AuthContext } from '../contexts/AuthContext';
import { articleService, categoryService, tagService } from '../services/api';
import { BsX } from 'react-icons/bs';

const ArticleForm = () => {
  const { id } = useParams();
  const navigate = useNavigate();
  const { user } = useContext(AuthContext);
  const isEditing = Boolean(id);
  
  const [article, setArticle] = useState({
    title: '',
    content: '',
    categoryId: '',
    tags: []
  });
  
  const [categories, setCategories] = useState([]);
  const [availableTags, setAvailableTags] = useState([]);
  const [newTagName, setNewTagName] = useState('');
  const [errors, setErrors] = useState({});
  const [loading, setLoading] = useState(true);
  const [saving, setSaving] = useState(false);
  const [error, setError] = useState(null);
  
  useEffect(() => {
    const fetchData = async () => {
      try {
        // 获取分类和标签数据
        const [categoriesRes, tagsRes] = await Promise.all([
          categoryService.getCategories(),
          tagService.getTags()
        ]);
        
        setCategories(categoriesRes.data);
        setAvailableTags(tagsRes.data);
        
        // 如果是编辑模式，获取文章数据
        if (isEditing) {
          const articleRes = await articleService.getArticleById(id);
          const articleData = articleRes.data;
          
          setArticle({
            title: articleData.title,
            content: articleData.content,
            categoryId: articleData.category?.id || '',
            tags: articleData.tags || []
          });
        }
        
        setLoading(false);
      } catch (err) {
        setError(isEditing ? '获取文章失败' : '初始化表单失败');
        setLoading(false);
      }
    };
    
    fetchData();
  }, [id, isEditing]);
  
  // 处理表单字段变化
  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setArticle({
      ...article,
      [name]: value
    });
    
    // 清除对应字段的错误
    if (errors[name]) {
      setErrors({
        ...errors,
        [name]: null
      });
    }
  };
  
  // 处理分类选择
  const handleCategoryChange = (e) => {
    setArticle({
      ...article,
      categoryId: e.target.value
    });
    
    if (errors.categoryId) {
      setErrors({
        ...errors,
        categoryId: null
      });
    }
  };
  
  // 添加标签
  const handleAddTag = () => {
    if (!newTagName.trim()) return;
    
    // 检查是否已存在相同标签
    const tagExists = article.tags.some(tag => 
      tag.name.toLowerCase() === newTagName.toLowerCase()
    );
    
    if (tagExists) {
      setErrors({
        ...errors,
        tags: '已添加相同标签'
      });
      return;
    }
    
    // 检查是否在可用标签中
    const existingTag = availableTags.find(tag => 
      tag.name.toLowerCase() === newTagName.toLowerCase()
    );
    
    if (existingTag) {
      // 添加已存在的标签
      setArticle({
        ...article,
        tags: [...article.tags, existingTag]
      });
    } else {
      // 添加新标签
      setArticle({
        ...article,
        tags: [...article.tags, { name: newTagName }]
      });
    }
    
    setNewTagName('');
    
    if (errors.tags) {
      setErrors({
        ...errors,
        tags: null
      });
    }
  };
  
  // 删除标签
  const handleRemoveTag = (index) => {
    const updatedTags = [...article.tags];
    updatedTags.splice(index, 1);
    
    setArticle({
      ...article,
      tags: updatedTags
    });
  };
  
  // 表单验证
  const validateForm = () => {
    const newErrors = {};
    
    if (!article.title.trim()) {
      newErrors.title = '请输入文章标题';
    }
    
    if (!article.content.trim()) {
      newErrors.content = '请输入文章内容';
    }
    
    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };
  
  // 表单提交
  const handleSubmit = async (e) => {
    e.preventDefault();
    
    if (!validateForm()) return;
    
    setSaving(true);
    
    try {
      const articleData = {
        ...article,
        // 将标签转换为API所需格式
        tags: article.tags.map(tag => tag.id ? tag : { name: tag.name })
      };
      
      if (isEditing) {
        // 更新文章
        await articleService.updateArticle(id, articleData);
      } else {
        // 创建新文章
        await articleService.createArticle(articleData);
      }
      
      // 导航到文章列表或文章详情页
      navigate(isEditing ? `/articles/${id}` : '/');
    } catch (err) {
      setError(isEditing ? '更新文章失败' : '创建文章失败');
      setSaving(false);
    }
  };
  
  if (loading) {
    return (
      <div className="flex justify-center py-8">
        <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-primary-600"></div>
      </div>
    );
  }
  
  if (!user) {
    return (
      <div className="max-w-4xl mx-auto px-4 py-8">
        <div className="bg-red-100 text-red-800 p-4 rounded-md">
          您需要登录后才能发布或编辑文章
        </div>
      </div>
    );
  }
  
  return (
    <div className="max-w-4xl mx-auto px-4 py-8">
      <h1 className="text-2xl font-bold mb-6 text-dark-800 dark:text-dark-200">
        {isEditing ? '编辑文章' : '创建新文章'}
      </h1>
      
      {error && (
        <div className="bg-red-100 text-red-800 p-4 rounded-md mb-6">
          {error}
        </div>
      )}
      
      <form onSubmit={handleSubmit} className="space-y-6">
        {/* 文章标题 */}
        <div>
          <label htmlFor="title" className="label">文章标题</label>
          <input
            type="text"
            id="title"
            name="title"
            value={article.title}
            onChange={handleInputChange}
            className={`input w-full ${errors.title ? 'border-red-500' : ''}`}
            placeholder="输入文章标题"
          />
          {errors.title && (
            <p className="text-red-500 text-sm mt-1">{errors.title}</p>
          )}
        </div>
        
        {/* 文章分类 */}
        <div>
          <label htmlFor="categoryId" className="label">文章分类</label>
          <select
            id="categoryId"
            name="categoryId"
            value={article.categoryId}
            onChange={handleCategoryChange}
            className={`input w-full ${errors.categoryId ? 'border-red-500' : ''}`}
          >
            <option value="">选择分类</option>
            {categories.map(category => (
              <option key={category.id} value={category.id}>
                {category.name}
              </option>
            ))}
          </select>
          {errors.categoryId && (
            <p className="text-red-500 text-sm mt-1">{errors.categoryId}</p>
          )}
        </div>
        
        {/* 文章标签 */}
        <div>
          <label className="label">文章标签</label>
          <div className="flex">
            <input
              type="text"
              value={newTagName}
              onChange={(e) => setNewTagName(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && (e.preventDefault(), handleAddTag())}
              className="input flex-grow"
              placeholder="输入标签名称并按回车添加"
            />
            <button
              type="button"
              onClick={handleAddTag}
              className="btn btn-primary ml-2"
            >
              添加
            </button>
          </div>
          
          {errors.tags && (
            <p className="text-red-500 text-sm mt-1">{errors.tags}</p>
          )}
          
          <div className="flex flex-wrap gap-2 mt-2">
            {article.tags.map((tag, index) => (
              <div 
                key={index} 
                className="flex items-center bg-gray-100 dark:bg-dark-700 px-3 py-1 rounded-full"
              >
                <span className="text-dark-700 dark:text-dark-300 mr-1">
                  {tag.name}
                </span>
                <button
                  type="button"
                  onClick={() => handleRemoveTag(index)}
                  className="text-gray-500 hover:text-red-500"
                >
                  <BsX />
                </button>
              </div>
            ))}
          </div>
        </div>
        
        {/* 文章内容 */}
        <div>
          <label htmlFor="content" className="label">文章内容</label>
          <textarea
            id="content"
            name="content"
            value={article.content}
            onChange={handleInputChange}
            className={`input w-full min-h-[300px] ${errors.content ? 'border-red-500' : ''}`}
            placeholder="输入文章内容，支持 Markdown 格式"
          ></textarea>
          {errors.content && (
            <p className="text-red-500 text-sm mt-1">{errors.content}</p>
          )}
        </div>
        
        {/* 提交按钮 */}
        <div className="flex justify-end gap-4">
          <button
            type="button"
            onClick={() => navigate(-1)}
            className="btn btn-secondary"
            disabled={saving}
          >
            取消
          </button>
          <button
            type="submit"
            className="btn btn-primary"
            disabled={saving}
          >
            {saving ? (
              <>
                <span className="animate-spin rounded-full h-4 w-4 border-t-2 border-b-2 border-white mr-2"></span>
                保存中...
              </>
            ) : (
              isEditing ? '更新文章' : '发布文章'
            )}
          </button>
        </div>
      </form>
    </div>
  );
};

export default ArticleForm; 